package com.droid.mvvmlib.base;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 分页Model
 *
 * @author zyc0617
 * @since 2019/8/18 15:35
 */
public class BasePagingModel<T> extends BaseModel<T> {

    protected boolean isRefresh = true;
    protected int offset = 0;

    protected void loadSuccess(T data, boolean isEmpty, boolean isRefresh, boolean isNextPage) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for (WeakReference<IBaseModeListener> weakListener : mWeakLinkArrayList) {
                    if (weakListener.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListener.get();
                        if (listener != null) {
                            int size = 0;
                            if (data instanceof List) {
                                size = (data == null) ? 0 : ((List<T>)data).size();
                            }
                            offset = isRefresh ? size: offset + size;
                            listener.onLoadFinish(BasePagingModel.this, data, isEmpty, isRefresh, isNextPage);
                        }
                    }
                }

                // 如果需要缓存数据，加载成功后缓存到preference中
                if (getCachedPreferenceKey() != null && isRefresh) {
                    saveToPreference(data);
                }

            }, 0);
        }
    }

    protected void loadFail(final String error, boolean isRefresh) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for (WeakReference<IBaseModeListener> weakListener : mWeakLinkArrayList) {
                    if (weakListener.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListener.get();
                        if (listener != null) {
                            listener.onLoadFail(BasePagingModel.this, error, isRefresh);
                        }
                    }
                }

            }, 0);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    protected void load() {

    }

    @Override
    protected void notifyCacheData(T data) {
        loadSuccess(data, false, true, false);
    }

    public interface IModelListener<T> extends IBaseModeListener {

        void onLoadFinish(BasePagingModel model, T data, boolean isEmpty, boolean isRefresh, boolean isNextPage);

        void onLoadFail(BasePagingModel model, String error, boolean isRefresh);
    }
}
